package org.tsinghua.answer.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.tsinghua.answer.domain.entity.PaginationInfo;
import org.tsinghua.answer.domain.question.Question;
import org.tsinghua.answer.domain.question.QuestionRepository;
import org.tsinghua.answer.domain.question.QuestionService;
import org.tsinghua.answer.domain.question.Reply;
import org.tsinghua.answer.domain.question.ReplyRepository;
import org.tsinghua.answer.domain.subject.Subject;
import org.tsinghua.answer.domain.subject.SubjectRepository;
import org.tsinghua.answer.domain.user.User;
import org.tsinghua.answer.utils.AuthUtils;

@Controller
@RequestMapping("volunteer")
public class VolunteerController {

	@Autowired
	private QuestionService questonService;
	@Autowired
	private QuestionRepository questionRepository;
	@Autowired
	private ReplyRepository replyRepository;
	@Autowired
	private SubjectRepository subjectRepository;
	
	@GetMapping("")
	public ModelAndView home(@RequestParam(value = "keyword", required=false) String keyword
			, @RequestParam(value = "page", defaultValue="0")Integer page
			, @RequestParam(value="size", defaultValue="20")Integer size
			, @RequestParam(value="answered", defaultValue="false") boolean answered
			, @RequestParam(value="subjectId", required=false) String subjectId) {
		User user = AuthUtils.getUser();
		String username = user.getNickname();
		if(username == null) {
			username = user.getUsername();
		}
		Page<Question> questions = questonService.volunteerQuestions(user.getId(), answered, subjectId, keyword, page, size);
		PaginationInfo pagination = new PaginationInfo(questions.getTotalPages(), questions.getNumber());
		List<Subject> subjects = subjectRepository.findAll();
		ModelAndView view = new ModelAndView("volunteer/home");
		view.addObject("username", username);
		view.addObject("questions", questions);
		view.addObject("answered", answered);
		view.addObject("subjectId", subjectId);
		view.addObject("keyword", keyword);
		view.addObject("pagination", pagination);
		view.addObject("subjects", subjects);
		return view;
	}
	
	@GetMapping("question/{id}")
	public ModelAndView question(@PathVariable("id") String id) {
		Question question = questionRepository.findOne(id);
		List<Reply> replies = replyRepository.findByQuestionId(id);
		ModelAndView view = new ModelAndView("question");
		view.addObject("question", question);
		view.addObject("replies", replies);
		view.addObject("domain", "volunteer");
		return view;
	}
}
